package models.re.aaa;

import java.util.ArrayList;
import java.util.List;

import models.re.IData;
import models.re.IRelation;
import models.re.ISimilarity;
import models.spider.stats.Stopwatch;


public class SubGraph {
	private IData data = null;
	//database.relation("the relation").type = All_Relations.index("the relation")-1
	/**
	 * scale_1: # of 1st degree neighbors
	 */
	
	public SubGraph(IData data) {
		this.data=data;
	}
		

	public ArrayList<String> GetNeighbors(String target)
	{
		Stopwatch wg = new Stopwatch();
		ArrayList<String> neighbors = new ArrayList<String>();
		int[] scale = {20,500,500};
		neighbors.add(target);
		
		for(int i=1;i<=3;i++){
			if(neighbors.size()<scale[1]){
				ArrayList<String> ngs = new ArrayList<String>(neighbors);
				for(String neis: ngs){
				neighbors = GetNeighborByRelation(neis, "belong",neighbors, scale[i-1]);
				neighbors = GetNeighborSimi(neis, neighbors, scale[i-1]);		
			}
		}
		System.out.println("with"+i+" degree neighrbos: "+neighbors.size());
		
		}	
//		System.out.println("all neighbors: "+neighbors);
		wg.stop();
		System.out.println("find neighbors cost " + wg.elapsed()/1000 + "s");

		return neighbors;
	}
	
	
	public ArrayList<String> GetNeighborSimi(
			String target, ArrayList<String> neighbors, int scale) {
		System.out.println("start Simi neighbors");
		ArrayList<ISimilarity> similarities = data.Similarity(Long.decode(target), 10);
//		System.out.println("simi size  "+similarities.size());
//		similarities= (ArrayList<ISimilarity>) similarities.subList(0, similarities.size());
		for(ISimilarity similarity: similarities) {
			String source = similarity.getSource().getStrId();
			String destination = similarity.getTarget().getStrId();
			if(!neighbors.contains(source))
				neighbors.add(source);
			if(!neighbors.contains(destination))
				neighbors.add(destination);
		}	
		return neighbors;
	}
	private ArrayList<String> GetNeighborByRelation (
			String target, String rel, ArrayList<String> neighbors, int scale) {
	List<IRelation> relations = data.findAllInRelation(rel,target);
	if(relations.size()>=scale) relations= relations.subList(0, scale);
	for(IRelation relation: relations) {
		String source = relation.getSource().getStrId();
		String destination = relation.getTarget().getStrId();
		if (!neighbors.contains(source))
			neighbors.add(source);
		if (!neighbors.contains(destination))
			neighbors.add(destination);
		}
	return neighbors;
	}	
	
	
	
}